const Service = require('egg').Service;
const _ = require('lodash')

class AppService extends Service {
    //创建token
    async createToken() {
        const { app, app: { model: { Company } } } = this
        let rows = await Company.findAll()
        for (let row of rows) {
            var ts = (new Date() - new Date(row.created_at)) / 1000
            if (!row.token || ts < 7100) {
                //重新获取token
                const ret = await app.curl(`https://oapi.dingtalk.com/gettoken?corpid=${row.corpid}&corpsecret=${row.secret}`, {
                    method: 'GET',
                    dataType: 'json',
                });
                row.token = ret.data.access_token;
                row.save()
            }
        }
    }

    //获取token
    async getToken(code) {
        const { app: { model: { Company } } } = this
        let row = await Company.findOne({
            where: {
                code
            },
        })
        var ts = (new Date() - new Date(row.created_at)) / 1000
        if (!row.token || ts < 7100) {
            //重新获取token
            const ret = await app.curl(`https://oapi.dingtalk.com/gettoken?corpid=${row.corpid}&corpsecret=${row.secret}`, {
                method: 'GET',
                dataType: 'json',
            });
            row.token = ret.data.access_token;
            row.save()
        }
        return row.token
    }

    //同步用户
    async getUser() {
        const { app: { dtalk, model: { Company } }, app, } = this;

        // 获取系统角色
        const roles = await app.table('role').findAll();

        // 获取通讯录 已授权部门列表
        const ret = await dtalk.auth.scopes();

        // 插入部门
        for (let deptId of ret.auth_org_scopes.authed_dept) {

            //获取该部门的子级部门列表
            const deptInfo = await dtalk.department.get(deptId);

            //获取子级部门列表
            const child_dept = await dtalk.department.list(deptInfo.id)

            let all_dept = [deptInfo]

            for (let child of child_dept.department) {
                all_dept.push(child)
            }

            //遍历所有部门
            for (let _dept of all_dept) {

                //保存部门
                await app.table('dept').upsert({
                    id: _dept.id,
                    name: _dept.name,
                    parentid: _dept.parentid,
                });

                // 获取部门用户
                const retUser = await dtalk.user.list({
                    department_id: _dept.id,
                });

                console.log(`部门: ${_dept.name} 人员总数: ${retUser.userlist.length}`);

                //循环写入用户
                for (let user of retUser.userlist) {
                    user.isAdmin = user.isAdmin ? 1 : 0;
                    user.isBoss = user.isBoss ? 1 : 0;
                    user.isHide = user.isHide ? 1 : 0;
                    user.isLeader = user.isLeader ? 1 : 0;
                    user.active = user.active ? 1 : 0;
                    user.department = user.department.join(',')
                    // 自动设置用户角色
                    const role = _.find(roles, { role_name: deptInfo.name });
                    if (role) {
                        user.role_id = role.id;
                    }

                    await app.table('user').upsert(user);
                }

            }

        }

        return ret
    }
}

module.exports = AppService